<template>
  <div class="organ-container">
    <h1>请选择一个组织进入</h1>
    <div class="organ-content">
      <div
        class="organ-content_item"
        v-for="item in organList"
        :key="item.organId"
        @click="handleChangeOrgan(item)"
      >
        <img
          :src="
            fileApi.imageUrl(
              item.logoUrl || '/wxapp/images/user/avatar.png',
              60,
              60,
            )
          "
          alt="logo"
        />
        <div style="margin-right: auto">{{ item.organName }}</div>
        <el-icon><ArrowRightBold /></el-icon>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { myorganList } from "@/api/auth/index";
import type { MyOrganModel } from "@/api/auth/types";
import { fileApi } from "@/api/file";
import { useUserStore } from "@/stores";
import type { LocationQuery, LocationQueryValue } from "vue-router";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 我的组织列表
const organList = ref<MyOrganModel[]>([]);
myorganList().then((res) => {
  if (res.data.results.length === 1) {
    handleChangeOrgan(res.data.results[0]);
  }
  organList.value = res.data.results;
});
// 切换组织
const handleChangeOrgan = (item: MyOrganModel) => {
  userStore.loginOrgan(item.tenant).then(() => {
    useUserStore().user.tenant = item.tenant;
    const query: LocationQuery = route.query;
    const redirect = (query.redirect as LocationQueryValue) ?? "/";
    const otherQueryParams = Object.keys(query).reduce(
      (acc: any, cur: string) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      },
      {},
    );
    otherQueryParams.tenant = item.tenant;

    router.push({ path: redirect, query: otherQueryParams });
  });
};
</script>

<style lang="scss" scoped>
.organ-container {
  width: 100vw;
  height: 100vh;
  overflow-y: auto;
  position: relative;
  background: var(--login-bg-url) no-repeat bottom right;
  background-size: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.organ-content {
  width: 30%;
  height: 50%;
  overflow-y: auto;
}

.organ-content_item {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
  cursor: pointer;
}
</style>
